package com.chatroomdemo.controller;

import com.chatroomdemo.model.Friend;
import com.chatroomdemo.model.User;
import com.chatroomdemo.service.FriendService;
import com.chatroomdemo.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public User login(String username, String password, HttpSession session) {
        log.info("用户登录：" + username);
        if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            return null;
        }
        User user = userService.queryUserByName(username);
        if (user != null && user.getPassword().equals(password)) {
            session.setAttribute("session_username", username);
            session.setAttribute("session_userId",user.getUserId());
            //返回之前对password进行处理
            user.setPassword("");
            return user;
        }
        log.warn("用户名或密码错误,{user}", user);
        return new User();//返回一个空对象
    }

    @PostMapping("/register")
    public User register(String username, String password) {
        log.info("注册用户:" + username + " " + password);
        User user = null;
        try {
            user = new User();
            if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
                return null;
            }
            user.setPassword(password);
            user.setUsername(username);
            int ret = userService.insertUser(user);
            user.setPassword("");//返回之前将password置空
        } catch (DuplicateKeyException e) {
            log.warn("注册失败，username：" + username);
            user = new User();
        }
        return user;
    }


    /**
     * @param: session,获取session中的username
     * @return: username + userId
     */
    @GetMapping("/userInfo")
    public User userInfo(HttpSession session) {
        log.info("session:" + session);
        if (session == null) {
            return new User();
        }
        User user = userService.queryUserByName((String)session.getAttribute("session_username"));
        if(user==null){
            log.info("user为空");
            return new User();
        }
        user.setPassword("");
        return user;
    }


}
